package com.zhuizikejithreeig.cn.threeigkeji.loginfo;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.zhuizikejithreeig.cn.been.ForgNumberBeen;
import com.zhuizikejithreeig.cn.content.ContectUtils;
import com.zhuizikejithreeig.cn.content.UriContect;
import com.zhuizikejithreeig.cn.threeigkeji.BasicActivity;
import com.zhuizikejithreeig.cn.threeigkeji.CompontApplayCation;
import com.zhuizikejithreeig.cn.threeigkeji.R;
import com.zhuizikejithreeig.cn.utils.GsonUtil;
import com.zhuizikejithreeig.cn.utils.PasswordNameSave;
import com.zhuizikejithreeig.cn.utils.ToastMake;
import com.zhuizikejithreeig.cn.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;
import java.util.Map;

import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import okhttp3.Call;
import okhttp3.MediaType;

public class ChengPawTwoActivity extends BasicActivity {

    private static final int CHENGPAWTWOACTIVITYREGIST = 200;
    private Button mSubmit;
    private EditText mNewPwd;
    private boolean hasPermission = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_cheng_paw_two);
        setLeftShow(1, R.mipmap.back);

        getLift_V().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        setTitle_V("更换密码");

        mNewPwd = (EditText) findViewById(R.id.name3);
        mSubmit = (Button) findViewById(R.id.name8);

        mSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.netConnected(ChengPawTwoActivity.this)) {
                    submit();
                }else {
                    ToastMake.showToast("网络异常,请检查网络");
                }
            }
        });
        hasPermission();

    }

    private void hasPermission() {

        //检查版本是否大于M
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M&&ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            PermissionGen.with(ChengPawTwoActivity.this)
                    .addRequestCode(CHENGPAWTWOACTIVITYREGIST)
                    .permissions(
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    )
                    .request();
            }else {
            hasPermission = true;
        }


    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = CHENGPAWTWOACTIVITYREGIST)
    public void requestPhotoSuccess() {
        //成功之后的处理
        //.......
        hasPermission = true;
    }

    @PermissionFail(requestCode = CHENGPAWTWOACTIVITYREGIST)
    public void requestPhotoFail() {
        //失败之后的处理，我一般是跳到设置界面
        hasPermission = false;

        boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(ChengPawTwoActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (showRequestPermission) {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            //        Uri uri = Uri.fromParts("package", context.getPackageName());
            //        intent.setData(uri);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        }

    }

    private void submit() {
        final String trim = mNewPwd.getText().toString().trim();
        if (TextUtils.isEmpty(trim)) {
            ToastMake.showToast("密码不能为空");
            return;
        }
        if (trim.length() < 6 || trim.length() > 25) {
            ToastMake.showToast("请输入6-25位长度的密码");
            return;
        }
        showProgrees("修改中,请稍等.....");
        Map<String, String> map = new HashMap<>();
        map.put("phone", Utils.getString(ContectUtils.PHONESAVE));
        map.put("pwd", trim);
        map.put("code", CompontApplayCation.registCode);
        final String json = GsonUtil.parseMapToJson(map);
        OkHttpUtils
                .postString()
                .url(UriContect.PASSWORD)
                .content(json)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastMake.showToast(getResources().getString(R.string.string58));
                        hideProgree();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        hideProgree();
                        ForgNumberBeen been = GsonUtil.parseJsonToBean(response, ForgNumberBeen.class);
                        if (been == null) {
                            ToastMake.showToast(getResources().getString(R.string.string58));
                            return;
                        }
                        if (!TextUtils.equals(been.getError_code(), "0")) {
                            ToastMake.showToast(been.getMsg());
                            return;
                        } else {
//                            ToastMake.showToast(been.getMsg());
                            Utils.setString(trim,ContectUtils.PASSWORLD);
                            //保存账号跟密码
                            if (Utils.sdIsOk() && hasPermission) {
                                PasswordNameSave.savePassword(ChengPawTwoActivity.this, Utils.getString(ContectUtils.PHONESAVE), trim, true);
                            } else {
                                ToastMake.showToast(getResources().getString(R.string.string43));
                            }
                            skipOtherActivity(SettingActivity.class, true);
                            finish();
                        }
                    }
                });
    }
}
